package com.surprise.base.util;

import java.io.IOException;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;

/**
 * HttpClientFluentUtils.java
 * @author nick
 * 2015年1月30日
 */
public class HttpClientFluentUtils {
    public static Request param(Request request, Map<String, String> params) {
        Form form = Form.form();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            form.add(entry.getKey(), entry.getValue());
        }
        return request.bodyForm(form.build());
    }

    public static String get(String uri, Map<String, String> params)
            throws IOException {
        return param(Request.Get(uri), params)
                .execute().returnContent().asString();
    }

    public static String get(String uri, Map<String, String> params,
            int connectTimeout, int socketTimeout) throws IOException {
        return param(Request.Get(uri), params)
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout)
                .execute().returnContent().asString();
    }

    public static String post(String uri, Map<String, String> params)
            throws IOException {
        return param(Request.Post(uri), params)
                .execute().returnContent().asString();
    }

    public static String post(String uri, Map<String, String> params,
            int connectTimeout, int socketTimeout) throws IOException {
        return param(Request.Post(uri), params)
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout)
                .execute().returnContent().asString();
    }

    public static RequestConfig.Builder getConfig() {
        return RequestConfig.custom();
    }
    
    public static String postJson(String url, String json) throws IOException {
        return Request.Post(url)
                .bodyString(json, ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
    }
    
    public static String postObjectAsJson(String url, Object obj) throws IOException {
        return Request.Post(url)
                .bodyString(JacksonUtils.toJson(obj), ContentType.APPLICATION_JSON)
                .execute()
                .returnContent()
                .asString();
    }
}
